function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
const ONEDAY = 1000*60*60*24;
function beforedays(timestamp){
  var date = new Date(timestamp);
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var days =[];
  var num=0;
  while(num<10){
    days.push(beforeday(timestamp-num*ONEDAY));
    num++;
  }
  return days.reverse();
}

function beforeday(timestamp){ 
  var date = new Date(timestamp-ONEDAY);
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  return {
      day:month+"/"+day,
      timestamp:timestamp-ONEDAY
  };
}
function beforeweeks(timestamp){
  var date = new Date(timestamp);
	var week = date.getDay();
  var currentFirstDate = addDate(date,week*-1);
  var weeks = [];
  var num=0;
  weeks.push(beforeweek(addDate(currentFirstDate,0)));
  while(num<4){
    weeks.push(beforeweek(addDate(currentFirstDate,-7)));
    num++;
  }
  return weeks.reverse();
}
function beforeweek(date){
  var day = date.getDate(); 
	var week = date.getDay()-1
  var month = date.getMonth()+1;
  var beforedate = tmpDate(date,-6);
  var beforemonth = beforedate.getMonth()+1;
  var beforeday = beforedate.getDate(); 
   return {
     week:beforemonth+"."+beforeday+"-"+month+"."+day,
     timestamp:Date.parse(beforedate)
   }
}
function addDate(date,n){
  date.setDate(date.getDate()+n); 
  return date;
};
function tmpDate(date,n){
  var tmp = new Date(date);
  tmp.setDate(date.getDate()+n);
  return tmp; 
}

function beforemonths(timestamp){
  var date = new Date(timestamp).toLocaleString();
  var arr = date.split('/');
  var year = arr[0]; //获取当前日期的年份
  var month = arr[1]; //获取当前日期的月份
  var day = arr[2]; //获取当前日期的日
  var days = new Date(year, month, 0);
  days = days.getDate(); //获取当前日期中月的天数
  var num=0;
  var months =[];
  while(num<5){
    var year2 = year;
    var month2 = parseInt(month) - 1;
    if (month2 == 0) {
        year2 = parseInt(year2) - 1;
        month2 = 12;
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
        day2 = days2;
    }
    var t2 =year!=year2?year2 + '-' + month2 :month2;
    year = year2;
    month = month2;
    months.push({
        month:t2,
        timestamp:Date.parse(new Date(year, month, 0))
    })
    num++
  }
  return months.reverse();
}


module.exports = {
  formatTime: formatTime,
  beforedays:beforedays,
  beforeweeks:beforeweeks,
  beforemonths:beforemonths
}

